package es.mgil.screenLocker;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings.SettingNotFoundException;
import android.provider.Settings.System;
import android.widget.RemoteViews;

public class ScreenLockerWidgetProvider extends AppWidgetProvider {
	static public final String CLICK = "es.mgil.screenLocker.WidgetApp.CLICK";
	public final int MIN_30 = 1800000;
	public final int MIN_1 = 60000;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		updateLayout(context);
	}

	@Override
	public void onEnabled(Context context) {
	}

	@Override
	public void onDisabled(Context context) {
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
		} else if (intent.getAction().equals(CLICK)) {
			switchState(context);
			updateLayout(context);
		} else {
			super.onReceive(context, intent);
		}
	}

	private boolean switchState(Context context) {
		int value = getTimeout(context);
		if (value == MIN_30) {
			System.putInt(context.getContentResolver(),
					System.SCREEN_OFF_TIMEOUT, MIN_1);
		} else {
			System.putInt(context.getContentResolver(),
					System.SCREEN_OFF_TIMEOUT, MIN_30);
		}
		return true;
	}

	private int getTimeout(Context context) {
		try {
			return System.getInt(context.getContentResolver(),
					System.SCREEN_OFF_TIMEOUT);
		} catch (SettingNotFoundException e) {
			return -1;
		}
	}

	private void updateLayout(Context context) {
		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget);

		views.setImageViewResource(R.id.Image,
				getTimeout(context) == MIN_30 ? R.drawable.icon_30
						: R.drawable.icon_1);

		ComponentName widget = new ComponentName(context,
				ScreenLockerWidgetProvider.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		assignClick(context, views);
		manager.updateAppWidget(widget, views);
	}

	private void assignClick(Context context, RemoteViews views) {
		Intent click_intent = new Intent(CLICK);
		PendingIntent pending_intent = PendingIntent.getBroadcast(context, 0,
				click_intent, 0);
		views.setOnClickPendingIntent(R.id.widgetLayout, pending_intent);
	}

}